//
//  LayerLogin.cpp
//  lhq
//
//  Created by codin on 14-7-24.
//
//

#include "LayerLogin.h"

USING_NS_CC;

Scene* LayerLogin::createScene() {
    auto scene = Scene::create();
    auto layer = LayerLogin::create();
    scene->addChild(layer);
    return scene;
}

bool LayerLogin::init() {
    if (!Layer::init()){
        return false;
    }
    
    auto director = Director::getInstance();
    
    Size visibleSize = director->getVisibleSize();
    Vec2 origin = director->getVisibleOrigin();
    
    auto bgSp = Sprite::create("texture/login/login_bg.jpg");
    bgSp->setPosition(Vec2(origin.x + visibleSize.width - bgSp->getContentSize().width/2,origin.y + bgSp->getContentSize().height/2));
    this->addChild(bgSp);
    
    auto loginItem = MenuItemImage::create("texture/login/login_btn1.png", "texture/login/login_btn1.png", CC_CALLBACK_1(LayerLogin::doLogin, this) );
    loginItem->setPosition(Vec2(origin.x + visibleSize.width/2+80,origin.y + visibleSize.height/2-80));
    
    //auto ttf0 = LabelTTF::create("Alignment 0\nnew line", "Helvetica", 12,Size(256, 32), TextHAlignment::LEFT);
    
    auto lb=LabelTTF::create("登     录.","Helvetica",50);
    lb->setPosition(Vec2(loginItem->getContentSize().width/2,loginItem->getContentSize().height/2));
    loginItem->addChild(lb);
    
    auto menu = Menu::create(loginItem, NULL);
    menu->setPosition(Vec2::ZERO);
    this->addChild(menu, 1);
    
    return true;
}

void LayerLogin::doLogin(Ref* sender) {
    log("doLogin");
	init_pomelo();

}
 void LayerLogin::init_pomelo()
{
	const char *ip = GATE_HOST;
    int port = GATE_PORT;

	Pomelo *pPomelo=Pomelo::getInstance();
	if(pPomelo->connect(ip,port))
	{
		return;
	}
	const char *route = "gate.gateHandler.queryEntry";
	json_t *msg = json_object();
	json_t *str = json_string(PLAYERUID);
	json_object_set(msg, "name", str);
	 json_decref(str);

	pPomelo->request(route,msg,this,callfuncND_selector(LayerLogin::requstGateCallback));
	
}

void LayerLogin::requstGateCallback(cocos2d::CCNode *node, void *resp)
{
	PomeloReponse* ccpomeloresp = (PomeloReponse*)resp;
	const char* connectorHost = json_string_value(json_object_get(ccpomeloresp->docs,"host"));
	int connectorPort = json_integer_value(json_object_get(ccpomeloresp->docs,"port"));
	
	Pomelo::getInstance()->stop();
    CCLOG("%s %d", connectorHost,connectorPort);
	if(Pomelo::getInstance()->connect(connectorHost,connectorPort))
	{
		return;
	}
	const char *route = "connector.entryHandler.login";
	json_t *msg = json_object();
	json_object_set(msg, "name", json_string(PLAYERUID));


	Pomelo::getInstance()->request(route,msg,this,callfuncND_selector(LayerLogin::requstConnectorCallback));
}
 void LayerLogin::requstConnectorCallback(cocos2d::CCNode *node, void *resp)
{
	
	PomeloReponse* ccpomeloresp = (PomeloReponse*)resp;

	int code = json_integer_value(json_object_get(ccpomeloresp->docs,"code"));
	
	if(code==200)
	{
		Director::getInstance()->replaceScene(LayerHall::createScene());
	}

 
 }
